package net.yxsoft.quorum;

import com.jfinal.kit.Prop;
import com.jfinal.plugin.IPlugin;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.admin.Admin;
import org.web3j.protocol.http.HttpService;
import org.web3j.quorum.Quorum;

public class QuorumPlugin implements IPlugin {

  private static Quorum quorum;
  private static Admin admin;
  private static Web3j web3j;

  private String nodeAddress;

  public QuorumPlugin(Prop configProp){

    nodeAddress = configProp.get("quorum.nodeAddress");

    if (QuorumKit.isBlank(nodeAddress)) {
      throw new IllegalArgumentException("The value of nodeAddress can not be blank.");
    } else {
      this.nodeAddress = nodeAddress;
    }
  }

  /**
   * 获取客户端链接
   * @return
   */
  private Quorum getQuorum(){
    if(quorum == null){
      synchronized (QuorumPlugin.class){
        if(quorum == null){
          quorum = Quorum.build(new HttpService(nodeAddress));
        }
      }
    }
    return quorum;
  }

  /**
   * 获取管理控制台
   * @return
   */
  private Admin getAdmin() {
    if (admin == null) {
      synchronized (QuorumPlugin.class) {
        if (admin == null) {
          admin = Admin.build(new HttpService(nodeAddress));
        }
      }
    }
    return admin;
  }

  /**
   * 获取连接
   * @return
   */
  public Web3j getWeb3j() {
    if (web3j == null) {
      synchronized (QuorumPlugin.class) {
        if (web3j == null) {
          web3j = Web3j.build(new HttpService(nodeAddress));
        }
      }
    }
    return admin;
  }

  @Override
  public boolean start() {

    QuorumKit.init(getQuorum(), getAdmin(), getWeb3j());
    return true;
  }

  @Override
  public boolean stop() {
    return true;
  }
}
